/**
 * 任务时间调度器，用于异步执行定时任务
 */
class TimeScheduler {
  constructor() {
    this.tasks = [];
    this.isRunning = false;
    this.isPaused = false;
    this.generator = null;
    this.pauseStartTime = 0;
    this.remainingDelay = 0;
    this.currentTask = null;
  }
  /**
   * 添加任务
   * @param {*} delay 延时时间
   * @param {*} callback 想要的执行逻辑
   * @returns
   */
  addTask(delay, callback) {
    this.tasks.push({ delay, callback });
    return this;
  }
  /**
   * 启动调度器
   * @returns
   */
  start() {
    if (this.isRunning) return;
    this.isRunning = true;
    this.isPaused = false;
    this.generator = this.taskGenerator();
    this.runGenerator();
  }
  /**
   * 暂停调度器
   * @returns
   */
  pause() {
    if (!this.isRunning || this.isPaused) return;
    this.isPaused = true;
    this.pauseStartTime = Date.now();
    // 如果有正在等待的任务，清除它的定时器
    if (this.currentTask && this.currentTask.timeoutId) {
      clearTimeout(this.currentTask.timeoutId);
      this.remainingDelay = this.currentTask.delay - (Date.now() - this.currentTask.startTime);
    }
  }
  /**
   * 恢复调度器
   * @returns
   */
  resume() {
    if (!this.isRunning || !this.isPaused) return;
    this.isPaused = false;
    // 如果有剩余延迟的任务，重新设置定时器
    if (this.currentTask && this.remainingDelay > 0) {
      this.currentTask.startTime = Date.now();
      this.currentTask.timeoutId = setTimeout(() => {
        this.currentTask.callback();
        this.runGenerator();
      }, this.remainingDelay);
    } else {
      this.runGenerator();
    }
  }
  /**
   * 停止调度器
   */
  stop() {
    this.isRunning = false;
    this.isPaused = false;
    // 清除当前任务的定时器
    if (this.currentTask && this.currentTask.timeoutId) {
      clearTimeout(this.currentTask.timeoutId);
    }
    this.currentTask = null;
    this.remainingDelay = 0;
  }
  /**
   * 任务生成器
   */
  * taskGenerator() {
    for (const task of this.tasks) {
      if (!this.isRunning) break;
      this.currentTask = {
        ...task,
        startTime: Date.now(),
        timeoutId: null
      };
      yield new Promise(resolve => {
        this.currentTask.timeoutId = setTimeout(() => {
          if (!this.isPaused) {
            task.callback();
            resolve();
          }
        }, task.delay);
      });
    }
  }
  /**
   * 运行生成器
   * @returns
   */
  runGenerator() {
    if (!this.isRunning || this.isPaused || !this.generator) return;
    const iteration = this.generator.next();
    if (iteration.done) {
      this.isRunning = false;
      return;
    }
    iteration.value.then(() => this.runGenerator());
  }
  /**
   * 获取当前状态
   * @returns
   */
  getStatus() {
    return {
      isRunning: this.isRunning,
      isPaused: this.isPaused,
      currentTask: this.currentTask,
      remainingDelay: this.remainingDelay
    };
  }
}

export default TimeScheduler;
